package main

import (
	"dbserver/config"
	"dbserver/service"
	"flag"
	"fmt"
	"os"
	"os/signal"
	"time"
	l "util/log"
)

var (
	path    string
	db      string
	allowip []string
	sync    = flag.Bool("sync", false, "sync database")
	help    = flag.Bool("help", false, "help")
	drop    = flag.Bool("drop", false, "Drop db, this option will drop db, be careful to use!!!!!!")
	useage  = "usage:dbmgr [-help] [-drop] [-sync]"
)

func main() {
	flag.Parse()
	if *help {
		fmt.Println(useage)
		flag.PrintDefaults()
		return
	}

	cfg := config.CreateConfig()
	if !cfg.Load() {
		l.TraceInfo("dbmgr", "load config failed")
		return
	}

	if !service.CreateDbService(cfg, *drop, *sync) {
		return
	}

	ch := make(chan bool)

	go service.StartTelnet(cfg, ch)

	l.TraceInfo("dbmgr", "running...")

	s := make(chan os.Signal, 1)
	signal.Notify(s, os.Interrupt)
	go func() {
		select {
		case <-s:
			ch <- true
		}
	}()

	select {
	case <-ch:
		break
	}

	l.TraceInfo("dbmgr", "shutdown...")
	service.StopDBService()
	service.StopTelnet()

	time.Sleep(5 * time.Second)

}
